//
//  MessageCenterManager.m
//  carcareIOS
//
//  Created by ileo on 16/9/1.
//  Copyright © 2016年 chezheng. All rights reserved.
//

#import "MessageCenterManager.h"
#import "MessageCenterViewModel.h"


@implementation MessageCenterManager

IMP_SINGLETON

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self initData];
    }
    return self;
}

-(void)updateSuccess:(void (^)())success fail:(void (^)())fail{
    __weak __typeof(self) wself = self;
    [NetMessageCenter messageCenterInfoSuccess:^(NSArray<MessageCenterModel *> *infos) {
        wself.messageCenterModels = infos;
        if (success) success();
    } fail:^{
        if (fail) fail();
    }];
}

-(void)readMessageType:(MessageCenter_Type)type messageID:(NSInteger)messageID{
    __weak __typeof(self) wself = self;
    [NetMessageCenter messageHadReadWithMessageType:type readID:messageID done:^{
        [wself updateSuccess:nil fail:nil];
    }];
}


-(void)initData{
    self.initStatus = ManagerDataIniting;
    __weak __typeof(self) wself = self;
    [self updateSuccess:^{
        wself.initStatus = ManagerDataInitSuccess;
    } fail:^{
        wself.initStatus = ManagerDataInitFail;
    }];
}
-(void)clearData{
    self.messageCenterModels = @[];
}

#pragma mark - view

-(UIViewController *)viewController{
    
    MessageCenterViewModel * viewModel = [[MessageCenterViewModel alloc]init];
    MessageCenterViewController *vc = [[[MessageCenterViewController alloc] initWithViewModel:viewModel] navSetupBackItemWithIdentification:BACK_ICON_TITLE];

    return vc;
}

#pragma mark - set get

-(void)setMessageCenterModels:(NSArray<MessageCenterModel *> *)messageCenterModels{
    _messageCenterModels = [messageCenterModels sortedArrayUsingComparator:^NSComparisonResult(MessageCenterModel   * _Nonnull obj1, MessageCenterModel   * _Nonnull obj2) {
        return obj1.type - obj2.type;
    }];
    NSInteger unReadNum = 0;
    for (MessageCenterModel *obj in messageCenterModels) {
        unReadNum += obj.unread;
    }
    self.unReadNum = unReadNum;
}

#pragma mark - receive notify

-(void)didReceiveUpdate:(ReceiveUpdateType)updateType{
    if (receiveUpdateContain(updateType, ReceiveAccountUpdate)) {
        [self clearData];
        [self initData];
    }
}

-(void)didReceiveMemoryWarning{
    [self clearData];
}

@end
